package com.alisls.demo.sso.server.listener;

import com.alisls.demo.sso.server.util.HttpUtil;
import com.alisls.demo.sso.server.util.TokenUtil;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.List;

/**
 * Session监听器
 *
 * @author Ke Wang
 */
@Component
public class SessionListener implements HttpSessionListener {

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        System.out.println("监听到session销毁，执行销毁方法");
        HttpSession session = se.getSession();
        String token = (String) session.getAttribute("token");

        // 调用每一个客户端的登出接口
        List<TokenUtil.SSOClient> ssoClients = TokenUtil.get(token);
        if (ssoClients != null) {
            for (TokenUtil.SSOClient ssoClient: ssoClients) {
                String clientLogoutUrl = ssoClient.getClientLogoutUrl();
                System.out.println("调用登出接口：" + clientLogoutUrl);
                HttpUtil.sendPost(clientLogoutUrl, ssoClient.getSessionId(), null);
            }
        }

        // 删除本地存储的token
        TokenUtil.remove(token);
        System.out.println("删除本地存储的token：" + token);
    }

}
